package com.loopy.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ManagerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //当Tomcat创建filter后会调用该方法初始化
        System.out.println("ManagerFilter  init()被调用");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //每次调用filter时候，该方法就会被调用
        System.out.println("ManagerFilter  doFilter()被调用");
        //如果要继续访问资源
        /*
        创建过滤器之前就已经封装好servletRequest，可以通过servletRequest获取很多信息
         */
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        Object username = session.getAttribute("username");
        if(username!=null){
            System.out.println("httpServletRequest="+httpServletRequest);
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            servletRequest.getRequestDispatcher("/login.jsp")
                    .forward(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {
//        当filter被销毁时该方法就会被调用
        System.out.println("ManagerFilter  destroy()被调用");
    }
}
